//
//  MusicRecommendTableViewController.m
//  XMLY
//
//  Created by lanou on 15/11/9.
//  Copyright © 2015年 曾杰. All rights reserved.
//

#import "MusicRecommendTableViewController.h"
#import "PKRequestManager.h"
#import "MusicViewCell.h"
#import "MusicRecommendHeadView.h"
#import "UIImageView+WebCache.h"
#import "SDCycleScrollView.h"
#import "MusicPlayViewController.h"
#import "ChildListModel.h"
#import "MusicDetailViewController.h"
#import "MoreListViewController.h"
#import "TopListViewController.h"
#import "CheckNetConnect.h"
#import "NetConnectView.h"
#define screen_width [UIScreen mainScreen].bounds.size.width
#define screen_height [UIScreen mainScreen].bounds.size.height
@interface MusicRecommendTableViewController ()<UIScrollViewDelegate,SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)NSMutableArray * rowArr;
@property (nonatomic, strong)NSMutableArray * sectionArr;
@property (nonatomic, strong)NSMutableDictionary * valueDic;
@property (nonatomic, strong) UIView * headview;
@property (nonatomic, strong)MusicRecommendHeadView * recommendView;
@property (nonatomic, strong)SDCycleScrollView * sdScrollview;
@property (nonatomic, strong)NSMutableArray * musicUrlArr;
@property (nonatomic, strong)NSMutableArray * headArr;
@property (nonatomic, strong)UINavigationController * naVC;
@property (nonatomic, strong) NetConnectView *connectView;
@property (nonatomic, strong)UITableView * mainTableView;
@property (nonatomic, strong)MoreListViewController * moreVC;
@end

@implementation MusicRecommendTableViewController


-(NSMutableArray *)headArr
{
    
    if (_headArr == nil) {
        self.headArr = [NSMutableArray array];
    }
    return _headArr;
    
}

-(NSMutableArray *)musicUrlArr
{
    if (_musicUrlArr == nil) {
        self.musicUrlArr = [NSMutableArray array];
    }
    return _musicUrlArr;
}

-(NSMutableDictionary *)valueDic
{
    if (_valueDic == nil) {
        self.valueDic = [NSMutableDictionary dictionaryWithCapacity:0];
    }
    return _valueDic;
}

-(NSMutableArray *)sectionArr
{
    if (_sectionArr == nil) {
        self.sectionArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _sectionArr;
}

-(void)requestData
{
    
    NSString * url = @"http://mobile.ximalaya.com/mobile/discovery/v2/category/recommends?categoryId=2&contentType=album&device=iPhone&scale=2&version=4.3.20";
    
    

    
 [PKRequestManager requestWithType:GET urlString:url parDic:nil finish:^(NSData *data) {
   
         NSDictionary * dic =[ NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
    
         NSDictionary * dict = [dic objectForKey:@"categoryContents"];
         NSDictionary * imagedic = [dic objectForKey:@"focusImages"];
         NSArray * lists = [imagedic objectForKey:@"list"];
         
         NSLog(@"%@",lists);
         for (int i = 0 ; i<lists.count; i++) {
             
             if ([lists[i] objectForKey:@"trackId"]) {
                 
                 [self.musicUrlArr addObject:[lists[i] objectForKey:@"pic"]];
                 [self.headArr addObject:[lists[i] objectForKey:@"trackId"]];
             }
         }
         [self setConfigureHeaderView];
         
         NSArray * array = [dict objectForKey:@"list"];
         NSArray * listArr = [array[0] objectForKey:@"list"];
         self.recommendView.topLabel.text =[listArr[0] objectForKey:@"title"];
         self.recommendView.titleLabel.text = [listArr[0] objectForKey:@"subtitle"];
         [self.recommendView.nextButton addTarget:self action:@selector(didClick:) forControlEvents:(UIControlEventTouchUpInside)];
         for (int i = 1 ; i<array.count; i++) {
             NSString * title = array[i][@"title"];
             [self.sectionArr addObject:title];
             NSArray * list = array[i][@"list"];
             _rowArr = [NSMutableArray arrayWithCapacity:0];
             for (NSDictionary * dictt in list) {
                 MusicModel * model = [[MusicModel alloc]init];
                 [model setValuesForKeysWithDictionary:dictt];
                 [self.rowArr addObject:model];
             }
             [self.valueDic setObject:self.rowArr forKey:title];
         }
         [self.mainTableView reloadData];
         

} error:^(NSError *error) {
    NSLog(@"%@",error);
}];

    
}

-(void)didClick:(UIButton *)button
{
    
    TopListViewController * topVC = [[TopListViewController alloc]init];
    topVC.key =@"ranking%3Aalbum%3Aplayed%3A1%3A2";
    topVC.titleStr =self.recommendView.topLabel.text;
    [self presentViewController:topVC animated:YES completion:nil];
    
}


- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    
    MusicPlayViewController * playVC = [[MusicPlayViewController alloc]init];
    playVC.trackId = self.headArr[index];
    [self presentViewController:playVC animated:YES completion:nil];
    
}

- (void)setConfigureHeaderView{
    
    _sdScrollview = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3-20 ) imageURLStringsGroup:self.musicUrlArr];
    _sdScrollview.delegate = self;
    _sdScrollview.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    _sdScrollview.autoScrollTimeInterval = 5.0;
    _sdScrollview.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    [_recommendView addSubview:_sdScrollview];
    self.mainTableView.tableHeaderView = _recommendView;
    
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, screen_height-100) style:(UITableViewStylePlain)];
    
    _recommendView = [[MusicRecommendHeadView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height/3+80)];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    [self.mainTableView registerClass:[MusicViewCell class] forCellReuseIdentifier:@"cell"];
    self.mainTableView.rowHeight =120;
    self.mainTableView.sectionHeaderHeight = 30;
    [self checkNetConnectState];
    
}
- (void)checkNetConnectState{
    
    BOOL netState = [[CheckNetConnect shareConnect] netConnectState];
    if (netState == YES) {
        NSLog(@"开始刷新数据");
        _connectView.frame = CGRectMake(0, - SCREEN_HEIGHT - 20, SCREEN_WIDTH, SCREEN_HEIGHT - 50) ;
        [self.view addSubview:_mainTableView];
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        [self requestData];
        
    }else{
        
        _connectView = [[NetConnectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.view addSubview:_connectView];
    }
    
}
// 重新请求数据
- (void)retryRequest{
    NSLog(@"重新刷新数据");
    [self checkNetConnectState];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.valueDic[self.sectionArr[section]] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MusicViewCell *cell = [self.mainTableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    MusicModel * model = self.valueDic[self.sectionArr[indexPath.section]] [indexPath.row];
    [cell configMusicCellWithModel:model];
    return cell;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView==self.mainTableView) {
        
        
        _headview = [[UIView alloc]initWithFrame:CGRectMake(0, 0,self.view.frame.size.width,20)];
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 140, 20)];
        label.text = self.sectionArr[section];
        label.font = [UIFont systemFontOfSize:15];
        [_headview addSubview:label];
        
        
        UILabel * moreLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width-80, 5, 80, 20)];
        moreLabel.backgroundColor = [UIColor whiteColor];
        moreLabel.text = @"更多  >";
        moreLabel.font = [UIFont systemFontOfSize:15];
        moreLabel.userInteractionEnabled = YES;
        moreLabel.tag = section+100;
        [_headview addSubview:moreLabel];
        UITapGestureRecognizer * recognizer =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(nextView:)];
        [moreLabel addGestureRecognizer:recognizer];
    }
    return _headview;
}

-(void)nextView:(UITapGestureRecognizer *)button
{
    
    NSString * title = self.sectionArr[button.view.tag-100];
    MoreListViewController * moreVC = [[MoreListViewController alloc]init];
    moreVC.categoryId=@"2";
    switch (button.view.tag-100) {
        case 0:
        {
            moreVC.tagName=@"";
        }
            break;
            
        case 1:
        {
            moreVC.tagName=@"%E7%B2%BE%E9%80%89%7C%E6%AD%8C%E5%8D%95";
        }
            break;
        case 2:
        {
            moreVC.tagName=@"%E7%BF%BB%E5%94%B1%7C%E7%BF%BB%E5%A5%8F";
        }
            break;
        case 3:
        {
            moreVC.tagName = @"%E4%B8%BB%E6%92%AD%7C%E8%8A%82%E7%9B%AE";
        }
            break;
            
        case 4:
        {
            moreVC.tagName = @"%E6%A6%9C%E5%8D%95%7C%E6%8E%92%E8%A1%8C";
        }
            break;
            
        case 5:
        {
            moreVC.tagName = @"%E8%89%BA%E4%BA%BA%7C%E6%98%8E%E6%98%9F";
        }
            break;
        case 6:
        {
            moreVC.tagName = @"%E6%80%80%E6%97%A7%7C%E7%BB%8F%E5%85%B8";
        }
            break;
        case 7:
        {
            moreVC.tagName = @"%E6%AC%A7%E7%BE%8E%7C%E5%85%B6%E4%BB%96";
        }
            break;
        case 8:
        {
            moreVC.tagName = @"%E7%9D%A1%E5%89%8D.%E5%82%AC%E7%9C%A0";
        }
            break;
        case 9:
        {
            moreVC.tagName = @"3D%E5%A5%87%E5%A6%99%E4%BD%93%E9%AA%8C%E9%A6%86";
        }
            break;
    }
    moreVC.titleStr =title;
    [self presentViewController:moreVC animated:YES completion:nil];
    
}


//设置区头随tableView滑动而滑动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView==self.mainTableView) {
        CGFloat sectionHeight = 30;
        if (scrollView.contentOffset.y<=sectionHeight&&scrollView.contentOffset.y>0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        }
        else if (scrollView.contentOffset.y>=sectionHeight)
        {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeight, 0, 0, 0);
        }
    }
    
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    MusicDetailViewController * detailVC = [[MusicDetailViewController alloc]init];
    MusicModel * model = self.valueDic[self.sectionArr[indexPath.section]][indexPath.row];
    detailVC.albumId = model.albumId;
    [self presentViewController:detailVC animated:YES completion:nil];
    
    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
